package top.yifengxiner.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author ：baixiao
 * @date ：Created in 2021/5/6 8:48
 * @description：redis工具类
 * @modified By：
 * @version: 0.0.1$
 */
@Component
public class RedisUtils
{
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 指定缓存失效时间
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key,long time)
    {
        try{
            if(time > 0)
            {
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取key值失效时间
     * @param key
     * @return
     */
    public long getExpire(String key)
    {
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }

    /**
     * 判断是否有key
     * @param key
     * @return
     */
    public boolean hasKey(String key)
    {
        return redisTemplate.hasKey(key);
    }

    /**
     * 缓存放入
     */
    public boolean set(String key,Object value)
    {
        try{
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }
}
